package uts.sdk.modules.oneoilNewland;

import android.content.Context;
import android.os.Bundle;
import android.os.RemoteException;
import com.newland.aidl.pinpad.PinPadCode;
import com.newland.aidl.rfcard.AidlRFCard;
import com.newland.aidl.rfcard.PowerOnRFResult;
import com.newland.aidl.rfcard.RFCardCode;

import uts.sdk.modules.oneoilNewland.R;
import uts.sdk.modules.oneoilNewland.NewlandService;
import uts.sdk.modules.oneoilNewland.ICallback;
import uts.sdk.modules.oneoilNewland.Response;
import uts.sdk.modules.oneoilNewland.CodecUtils;
import io.dcloud.uts.*;

public class RfCardAction {
	private AidlRFCard cardReader;
	
	private String snr;
	
    private RfCardAction() {
		cardReader = NewlandService.getRFCardReader();
	}
    
    // 静态内部类不会在外部类加载时立即加载
    private static class RfCardActionHolder {
        private static final RfCardAction INSTANCE = new RfCardAction();
    }
    
    // 第一次调用时才会加载SingletonHolder类
    public static RfCardAction getInstance() {
        return RfCardActionHolder.INSTANCE;
    }
	
	public boolean powerOn(int rfcType) throws RemoteException {
		int[] cardType = new int[3];
		switch(rfcType) {
			case RFCardCode.RFCType.ACARD:
				cardType[0] = RFCardCode.RFCType.ACARD;
				break;
			case RFCardCode.RFCType.BCARD:
				cardType[1] = RFCardCode.RFCType.BCARD;
				break;
			case RFCardCode.RFCType.M1CARD:
				cardType[2] = RFCardCode.RFCType.M1CARD;
			    break;
			default:
				return false;
		}
		PowerOnRFResult qPResult = cardReader.powerOn(cardType,30);
		if (qPResult == null) {
			return false;
		}
		
		if (qPResult.getCardSerialNo() != null) {
			this.snr = CodecUtils.hexString(qPResult.getCardSerialNo());
			if(this.snr.length()>8){
				this.snr = this.snr.substring(this.snr.length()-8);
			}
		}
		
		return true;
	}
	
	public boolean powerOff() throws RemoteException {
		cardReader.powerOff();
		return true;
	}
	
	public boolean authenticateByExtendKey(int qpKeyMode, int block, String keyStr) {
		byte sn[] = null;
		if (this.snr != null) {
			sn = CodecUtils.hex2byte(this.snr);
		} else {
			return false;
		}
		byte key[] = CodecUtils.hex2byte(keyStr);
		if (block >= 0 && block <= 255 && key.length == 6 && sn!=null && sn.length == 4) {
			try {
				return cardReader.authenticate(qpKeyMode, sn, block, key);
			}catch (Exception e){
				e.printStackTrace();
			}
		}
		return false;
	}
	
	public String cardRead(int block) throws Exception {
		if (block >= 0 && block <= 255) {
			byte output[] = cardReader.readData(block);
			return CodecUtils.hexString(output);
		}
		return null;
	}
}